# -*- coding: UTF-8 -*-

import pandas as pd
from datetime import datetime
from pprint import pprint

from config import config
import numpy as np
import pymongo
import os
import time
import re
import threading
from dash_lib.mongodb_helper import mongo_db

pending_list = []
pending_a_list = []


def filter(df, query_array):
    filtered_df = df
    if query_array:
        for item in query_array:
            filtered_df = filtered_df.query(item)
    return filtered_df


def init():
    pd.options.display.float_format = '{:,.1f}'.format
    pd.set_option('display.height', 1000)
    pd.set_option('display.max_rows', 500)
    pd.set_option('display.max_columns', 700)
    pd.set_option('display.width', 1000)
    pd.options.mode.chained_assignment = None  # default='warn'


def init_df_from_db():
    print('start analyse :')
    find__sort = mongo_db.feed.find().sort('last_update', pymongo.DESCENDING)
    data_frame = pd.DataFrame(list(find__sort))
    if not data_frame.empty:
        del data_frame["_id"]
    data_frame.sort_values(['last_update'], ascending=False)

    # data_frame = data_frame[
    #     [('group_index', ''), ('len', 'profit'), ('mean', 'profit'), ('median', 'profit'), ('sum', 'profit'),
    #      ('amax', 'profit')]]
    # data_frame.columns = ['stake' if is_stake else 'type', ' len', 'mean', 'median', 'sum', 'max']
    data_frame = data_frame.round(2)
    return data_frame


def notify(title, text):
    for index in range(1):
        time.sleep(2)

        os.system("""     osascript -e 'display notification "{}" with title "{}"'
                  """.format(text, title))
        os.system('say "{} {}" '.format(title, text))


def get_filler_array():
    query_array = []
    # query_array.append('pick_type==["Single"]')
    query_array.append('result==["PENDING"]')
    # query_array.append('sport==["Football"]')
    return query_array
    # tipper stake  pick_tpye  sport


def format_quert(limit):
    _query = {'tipper': limit['tipper'],
              '$and': [{'stake': {'$lte': limit['stake'][1]}}, {'stake': {'$gte': limit['stake'][0]}}]}

    if limit['sport'] == 'All' and limit['pick_type'] == 'All':
        pass
    elif limit['sport'] == 'All':
        _query['pick_type'] = limit['pick_type']
    elif limit['pick_type'] == 'All':
        _query['sport'] = limit['sport']
    return _query


def get_db_feed_list(is_read):
    limits = list(mongo_db.rate.find())
    A_LIST = []
    B_LIST = []
    for limit in limits:
        query_format = format_quert(limit)
        query_format['result'] = 'PENDING'
        query_format['is_read'] = '1' if is_read else {"$ne": '1'}
        found = list(mongo_db.feed.find(query_format))
        if len(found):
            if limit['score'] == 5:
                B_LIST.extend(found)
            elif limit['score'] == 10:
                A_LIST.extend(found)

    global pending_list, pending_a_list
    pending_a_list = A_LIST
    pending_list = []
    pending_list.extend(A_LIST)
    pending_list.extend(B_LIST)
    return pending_list


def get_table_source(is_read):
    total_list = get_db_feed_list(is_read)
    frame = pd.DataFrame(total_list)
    if frame.empty:
        return [{}]
    del frame["_id"]
    frame = frame.round(2)
    frame = sort_df_order(frame)
    frame = frame.sort_values(['last_update'], ascending=False)

    return frame.to_dict('records')


def sort_df_order(dataframe):
    if not dataframe.empty:
        # dataframe['group_index'] = dataframe.index
        # dataframe = dataframe[
        #     'book_maker', 'category', 'is_read', 'kickoff', 'kickoff_time', 'last_update', 'match', 'odd', 'pick', 'pick_type', 'profit', 'result', 'sport', 'stake', 'tipper']
        dataframe = dataframe[
            ['is_read', 'tipper', 'pick_type', 'sport', 'stake', 'book_maker', 'odd', 'category', 'kickoff', 'match',
             'kickoff_time', 'last_update', 'pick', 'profit', 'result']]
    return dataframe


def refresh():
    if len(pending_list):
        for item in pending_list:
            level_tip = 'high  confidence ' if item in pending_a_list else 'Normal'
            notify(
                '{} tip  coming ！,{} has a {} level {} tip '.format(level_tip, item['tipper'],
                                                                    level_tip,
                                                                    item['sport']), ' ')


def loop_refresh():
    print('loop_refresh', datetime.now())
    refresh()
    global timer
    timer = threading.Timer(100, loop_refresh)
    timer.start()


def start_loop_notify():
    print('start_loop', datetime.now().strftime('%d %b, %H:%M'))
    timer = threading.Timer(3, loop_refresh)
    timer.start()
